<script lang="ts">
import {defineComponent, onMounted, reactive, toRefs, watch} from 'vue'
import type {MenuItem} from '../../types/menu'
import {
  useLocalStore
} from '../../store/local.js'
import {
  storeToRefs
} from 'pinia'
import {
  Menu,
  Management
} from '@element-plus/icons-vue'
import {
  useRoute
} from 'vue-router'

interface SideMenuProps {
  menuList: MenuItem[]
  activeId: string
}

export default defineComponent({
  name: 'SideMenu',
  components: {
    Menu,
    Management
  },
  emits: ['change', 'select'],
  props: {
    menuList: {
      type: Array as () => MenuItem[],
      required: true
    },
    activeId: {
      type: String,
      default: ''
    }
  },
  setup(props: SideMenuProps, { emit }) {
    const state = reactive({
      isCollapsed: false
    })

    const route = useRoute()

    const localStore = useLocalStore()

    const {collapse} = storeToRefs(localStore)

    onMounted(() => {
      state.isCollapsed = collapse.value
    })

    watch(() => collapse.value, (e) => {
      state.isCollapsed = e
    })

    const handleClick = (item: MenuItem) => {
      if (item.handler) {
        item.handler()
      } else {
        emit('change', item)
      }
    }

    const handleSelect = (index: string) => {
      emit('select', index)
    }

    return {
      ...toRefs(state),
      route,
      handleClick,
      handleSelect
    }
  }
})
</script>

<template>
  <el-menu :collapse="isCollapsed"
           :default-active="activeId"
           :collapse-transition="false"
           background-color="transparent"
           text-color="#fff"
           @select="handleSelect">
    <template v-for="item in menuList" :key="item.id">
      <!-- 带子菜单的项 -->
      <el-sub-menu v-if="item.children" :index="item.path">
        <template #title>
          <el-icon>
            <Menu />
          </el-icon>
          <span>{{ item.title }}</span>
        </template>
        <SideMenu
            :menu-list="item.children"
            :active-id="activeId"
            @select="handleSelect"
        />
      </el-sub-menu>

      <!-- 叶子节点 -->
      <el-menu-item
          v-else
          :index="item.path"
          @click="handleClick(item)"
      >
        <el-icon>
          <Menu />
        </el-icon>
        <span>{{ item.title }}</span>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<style lang="scss">
.el-menu.el-menu--vertical {
  border-right: none;
}
</style>